<?php
//User interface that allows a user to complete a newly created inspection or finish an inspection in progress.
	include 'templateHandler.php';
	include 'commonAccountFunctions.php';
	
	//The User clicked save or submit completed on viewCheckList.php
	$arrayOfStrings = readTemplate($_REQUEST["protocol"]);
	$parsedTemplate = parseTemplateLines($arrayOfStrings);
	$fileInfo = $parsedTemplate["fileInfo"];
	
	$facility=$_REQUEST["facility"];
	$time=$_REQUEST["time"];
	$date=$_REQUEST["date"];
	$protocol=trim($_REQUEST["protocol"]);
	if(trim($_REQUEST["suffix"]) != ""){
		$suffix = "_" . trim($_REQUEST["suffix"]);
		$protocol = substr($protocol, 0, -4);
		$fileName = $facility . "_" . $time . "_" . $date . "_" . $protocol . $suffix . ".txt";
	} else{ 
		$suffix = "";
		$fileName = $facility . "_" . $time . "_" . $date . "_" . $protocol;
	}
	if($_REQUEST["save"] == "save"){	//user selected save as incomplete
		$saveLocNum = 0;
	}
	else{ //user selected save completed
		$saveLocNum = 1;
	}
	
//######################################################################################
//loads an empty template into an array and then begins to fill in information by loading
//information from $_REQUEST[], and then returns data as a string
function buildSave($arrayOfGroups, $complete){
	$quesList = "";
	$stringFileInfo = labeled_array_get($_REQUEST, "facility", "Facility") .
	                  labeled_array_get($_REQUEST, "time", "Time") .
					  labeled_array_get($_REQUEST, "date", "Date") .
					  labeled_array_get($_REQUEST, "protocol", "Protocol") .
					  labeled_array_get($_REQUEST, "inspector", "Inspector") .
					  "Complete: " . $complete . "\n";
	foreach($arrayOfGroups as $group){
		$stringFileInfo = $stringFileInfo . "G: " . $group["heading"] . "\n";
		foreach($group["questions"] as $quesData){
			$photoName = photoInputName($quesData["quesNum"], $quesData["groupNum"]);
			$quesList = $quesList . "Q: " . $quesData["question"] . "\n";
			$quesList = $quesList . "A: " . array_get($_REQUEST, radioButtonName($quesData["quesNum"], $quesData["groupNum"])). "\n";
			$quesList = $quesList . "C: " . array_get($_REQUEST, commentInputName($quesData["quesNum"], $quesData["groupNum"])) . "\n";
			if(array_get($_REQUEST, $photoName) == ""){
				if(isset($_FILES[$photoName])){
					$photoName2 = savePhoto($photoName);
				}else{ $photoName2 = "";}
			}
			else{ $photoName2 = array_get($_REQUEST, $photoName);}
			$quesList = $quesList . "P: " . $photoName2 . "\n";
		}
		$stringFileInfo = $stringFileInfo . $quesList;
		$quesList = "";
	}
	return trim($stringFileInfo);
}

// http://webcheatsheet.com/php/create_thumbnail_images.php
/*function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth ) 
{
  // open the directory
  $dir = opendir( $pathToImages );

  // loop through it, looking for any/all JPG files:
  while (false !== ($fname = readdir( $dir ))) {
    // parse path for the extension
    $info = pathinfo($pathToImages . $fname);
    // continue only if this is a JPEG image
    if ( strtolower($info['extension']) == 'jpg' ) 
    {
      echo "Creating thumbnail for {$fname} <br />";

      // load image and get image size
      $img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
      $width = imagesx( $img );
      $height = imagesy( $img );

      // calculate thumbnail size
      $new_width = $thumbWidth;
      $new_height = floor( $height * ( $thumbWidth / $width ) );

      // create a new temporary image
      $tmp_img = imagecreatetruecolor( $new_width, $new_height );

      // copy and resize old image into new image 
      imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

      // save thumbnail into a file
      imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
    }
  }
  // close the directory
  closedir( $dir );
}*/

function savePhoto($photoName){
	$facility=$_REQUEST["facility"];
	$time=$_REQUEST["time"];
	$date=$_REQUEST["date"];
	$protocol=trim($_REQUEST["protocol"]);
	if(trim($_REQUEST["suffix"]) != ""){
		$suffix = "_" . trim($_REQUEST["suffix"]);
	} else{ $suffix = "";}
	$fileName = $facility . "_" . $time . "_" . $date . "_" . substr($protocol, 0, -4) . $suffix . "_" . $photoName . "." . substr($_FILES[$photoName]["type"], 6);
	if($_FILES[$photoName]["error"] > 0){
		//file does not exist or was not uploaded correctly.
		$fileName = "";
	}
	else{
		//if uploaded file exists and it is gif, jpeg, pjpeg, or png and it is less than 2 mb save photo.
		if ((($_FILES[$photoName]["type"] == "image/gif")
			|| ($_FILES[$photoName]["type"] == "image/jpeg")
			|| ($_FILES[$photoName]["type"] == "image/pjpeg")
			|| ($_FILES[$photoName]["type"] == "image/png"))
			&& ($_FILES[$photoName]["size"] < 2048000)) {
			  
			if (file_exists("../files/pictures/" . $_FILES[$photoName]["name"])) {
				echo $_FILES[$photoName]["name"] . " already exists. ";
			}
			else{
				move_uploaded_file($_FILES[$photoName]["tmp_name"], "../files/pictures/" . $fileName);
				echo "Stored in: " . "../files/pictures/";
			}
		}
		else{ $fileName = "";}
	}
	//createThumbs("../files/pictures/$fileName", "../files/thumbnails/", 100);
	return $fileName;
}

//######################################################################################
//saves a given file to either incompleteInspections or CompleteInspections based on the saveLocNum
function store($fileName, $data, $saveLocNum, $isNewFile = false){
	if($saveLocNum == 0){
		$fileName = "../files/incompleteInspections/" . trim($fileName);
	}
	else{
		$fileName = "../files/completedInspections/" . trim($fileName);
	}
	
	if ($isNewFile){  // check to ensure no name conflict
		$suffix = 1;
		$basefileName = removeExtension($fileName);
		while (file_exists($fileName)){
				$fileName = $basefileName . "_($suffix).txt";
				$suffix+=1;
		}
	}
		
	$fh = fopen($fileName, 'w') or die("can't open file");
	if(fwrite($fh, $data) === False){
		echo "failed to write data to file";
	}
	else{ } //do nothing
	fclose($fh);
}

// removeExtension: string -> string
// removes the .txt extension from the file name
function removeExtension($file){
        return substr($file, 0, -4);
}

function checkComplete($arrayOfGroups){
	$isComplete = 1;
	$groupNum = 1;
	$quesNum = 1;
	$incomplete = "";
	echo "<pre>";
	foreach($arrayOfGroups as $group){
		foreach($group["questions"] as $quesData){
			$radioNum = "r_" . $groupNum . "_" . $quesNum;
			if(isset($_REQUEST[$radioNum]) && $_REQUEST[$radioNum]!=""){
				//echo "$radioNum = ";
				//print($_REQUEST[$radioNum]);
				//echo "\n";	
			}
			else{ 
				$isComplete = 0;
				$incomplete = $radioNum . $incomplete; 
				//echo "$radioNum =  \n";
			}
			$quesNum++;
		}
			$groupNum++;
			$quesNum = 1;
	}
	//echo "isComplete = $isComplete \n";
	//echo "</pre>";
	$ret["isComplete"] = $isComplete;
	$ret["incomplete"] = $incomplete;
	return $ret;
}
	//print($saveLocNum);

	if($saveLocNum == 0){
		//Show file saved correctly or fail.
		//echo "<pre>";
		$data = buildSave($parsedTemplate["groups"], 0);
		store($fileName, $data, $saveLocNum, $_REQUEST["isNewFile"]);
		//echo "</pre>";
		?> <script type="text/javascript">
			<!--
			window.location = "controlpanel.php"
			//-->
		</script> <?php
	}else{ //check to see if file is completed.
		$ret = checkComplete($parsedTemplate["groups"]);
		$isComplete = $ret["isComplete"];
		$incomplete = $ret["incomplete"];
		//print_r($incomplete);
		//print($isComplete);
		if($isComplete != 0){
			//echo "<pre>";
			$data = buildSave($parsedTemplate["groups"], 1);
			store($fileName, $data, 1, $_REQUEST["isNewFile"]);
			//echo "saving in completedInspections";
			//echo "<pre>";
			//delete the file located in incomplete inspections
			unlink("../files/incompleteInspections/" . $fileName); ?>
			<script type="text/javascript">
			<!--
			window.location = "controlpanel.php"
			-->
			</script> <?php
		} else{ //all radio buttons have not been assigned
			//save file data and reload in viewChecklist.php
			$data = buildSave($parsedTemplate["groups"], 0);
			store($fileName, $data, 0, $_REQUEST["isNewFile"]);
			//echo "file saved succesfully in incompleteInspections"; ?>
	
			<form action="viewCheckList.php" name="thisForm" method="post">
				<input type="hidden" name="file" value="<?=substr($fileName, 0, -4)?>"/>
				<input type="hidden" name="notCom" value="The inspection is not complete. Please make sure all questions have been answered, (Yes, No, N/A)
															Or save the inspection for later by clicking 'save' instead of 'submit completed'."/>
				<input type="hidden" name="incomplete" value="<?=$incomplete?>"/>
			</form>
			<script type="text/javascript">
			document.thisForm.submit();
			</script>
	<?php }
	}
	?>